package com.renwei.yunlong.activity.contacts;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.me.PersonChooseActivity;
import com.renwei.yunlong.activity.news.GroupChooseActivity;
import com.renwei.yunlong.activity.work.GuideWebActivity;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.EmpSaveOwnerJsonBean;
import com.renwei.yunlong.bean.EmpSaveServiceJsonBean;
import com.renwei.yunlong.event.ContactsRefreshEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.zyf.fwms.commonlibrary.utils.FormatUtil;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

/**
 * 添加员工--页面
 * <p>
 * Created by Administrator on 2017/8/29.
 */

public class AddEmployeeActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener {

    private static final int REQUEST_DEPARTMENT = 10;
    private static final int REQUEST_GROUP = 11;
    private static final int REQUEST_PERSON = 12;
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_edit)
    TextView tvEdit;
    @Bind(R.id.iv_cont)
    ImageView ivCont;
    @Bind(R.id.iv_edit)
    ImageView ivEdit;
    @Bind(R.id.iv_contacts)
    ImageView ivContacts;
    @Bind(R.id.iv_more)
    ImageView ivMore;
    @Bind(R.id.iv_scroll)
    ImageView ivScroll;
    @Bind(R.id.et_name)
    EditText etName;
    @Bind(R.id.rl_name)
    RelativeLayout rlName;
    @Bind(R.id.et_number)
    EditText etNumber;
    @Bind(R.id.rl_job_number)
    RelativeLayout rlJobNumber;
    @Bind(R.id.et_phone)
    EditText etPhone;
    @Bind(R.id.rl_login)
    RelativeLayout rlLogin;
    @Bind(R.id.btn_man)
    Button btnMan;
    @Bind(R.id.btn_woman)
    Button btnWoman;
    @Bind(R.id.rl_sex)
    RelativeLayout rlSex;
    @Bind(R.id.tv_department)
    TextView tvDepartment;
    @Bind(R.id.iv_department)
    ImageView ivDepartment;
    @Bind(R.id.rl_department)
    RelativeLayout rlDepartment;
    @Bind(R.id.tv_zhineng)
    TextView tvFunction;
    @Bind(R.id.iv_grouping)
    ImageView ivGrouping;
    @Bind(R.id.rl_grouping)
    RelativeLayout rlGrouping;
    @Bind(R.id.tv_character)
    TextView tvCharacter;
    @Bind(R.id.iv_character)
    ImageView ivCharacter;
    @Bind(R.id.rl_character)
    RelativeLayout rlCharacter;
    @Bind(R.id.btn_start)
    Button btnStart;
    @Bind(R.id.btn_close)
    Button btnClose;
    @Bind(R.id.rl_status)
    RelativeLayout rlStatus;
    @Bind(R.id.et_mail)
    EditText etMail;
    @Bind(R.id.rl_email)
    RelativeLayout rlEmail;
    @Bind(R.id.et_mobile)
    EditText etMobile;
    @Bind(R.id.rl_phone)
    RelativeLayout rlPhone;
    @Bind(R.id.btn_nan)
    Button btnNan;
    @Bind(R.id.btn_nv)
    Button btnNv;
    @Bind(R.id.rl_contact)
    RelativeLayout rlContact;
    @Bind(R.id.btn_determine_add)
    Button btnDetermineAdd;
    private String departId;  // 部门id
    private String personId;
    private int isForeign = 0; //是否是对外联系人（0否，1是）
    private int engineerStatus = 1; //（1启用，2挂起）
    private int gender = 1; //性别（0女，1男）
    private HashMap<String, String> groupMap;
    private String[] arry;


    /*
    * jsonBean={"name":"员工姓名"、"employeeCode":"员工工号"、"mobilePhone":"登录手机"、"gender":"性别（0女，1男）、
    * "departmentId":"所属部门ID"、"roleId":"关联角色ID"、"email":"电子邮箱"、"officeTelephone":"办公电话"、
    * "isForeign":"是否是对外联系人（0否，1是）"、"engineerStatus":"当前状态（1启用，2挂起）"、"creatorId":"操作人ID"、
    * "userGroupId":"职能分组ID"、"serviceProviderCode":"当前登录人公司code"}*/
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_employee);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        initData();

    }

    private void initData() {
        tvTitle.setText("添加员工");
        Drawable titleLeft = getResources().getDrawable(R.mipmap.icon_title_help);
        titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
        tvTitle.setCompoundDrawables(null, null, titleLeft, null);
        tvTitle.setCompoundDrawablePadding(10);
        arry = new String[1];
        ivBack.setVisibility(View.VISIBLE);
        tvTitle.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        rlName.setOnClickListener(this);
        rlJobNumber.setOnClickListener(this);
        rlLogin.setOnClickListener(this);
        btnMan.setOnClickListener(this);
        btnWoman.setOnClickListener(this);
        rlDepartment.setOnClickListener(this);
        rlGrouping.setOnClickListener(this);
        rlCharacter.setOnClickListener(this);
        btnStart.setOnClickListener(this);
        btnClose.setOnClickListener(this);
        btnNan.setOnClickListener(this);
        btnNv.setOnClickListener(this);
        rlEmail.setOnClickListener(this);
        rlPhone.setOnClickListener(this);
        rlContact.setOnClickListener(this);
        btnDetermineAdd.setOnClickListener(this);
        etName.setFilters(new InputFilter[]{AppHelper.emojiFilter});
        etMail.setFilters(new InputFilter[]{AppHelper.emojiFilter});
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.tv_title:
                GuideWebActivity.openActivity(this, Api.$().GUIDE_ADD_EMP_URI);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_job_number://员工工号
                break;
            case R.id.rl_login://登录手机
                break;
            case R.id.btn_man://男
                gender = 1;
                btnMan.setBackgroundResource(R.drawable.shape_rb_left_pre);
                btnMan.setTextColor(getResources().getColor(R.color.white));
                btnWoman.setBackgroundResource(R.drawable.shape_rb_right_nor);
                btnWoman.setTextColor(getResources().getColor(R.color.color_333333));
                break;
            case R.id.btn_woman://女
                gender = 0;
                btnMan.setBackgroundResource(R.drawable.shape_rb_left_nor);
                btnMan.setTextColor(getResources().getColor(R.color.color_333333));
                btnWoman.setBackgroundResource(R.drawable.shape_rb_right_pre);
                btnWoman.setTextColor(getResources().getColor(R.color.white));
                break;
            case R.id.btn_nan://
                isForeign = 1;
                btnNan.setBackgroundResource(R.drawable.shape_rb_left_pre);
                btnNan.setTextColor(getResources().getColor(R.color.white));
                btnNv.setBackgroundResource(R.drawable.shape_rb_right_nor);
                btnNv.setTextColor(getResources().getColor(R.color.color_333333));
                break;
            case R.id.btn_nv://
                isForeign = 0;
                btnNan.setBackgroundResource(R.drawable.shape_rb_left_nor);
                btnNan.setTextColor(getResources().getColor(R.color.color_333333));
                btnNv.setBackgroundResource(R.drawable.shape_rb_right_pre);
                btnNv.setTextColor(getResources().getColor(R.color.white));
                break;
            case R.id.rl_department://部门
                DepartmentChooseActivity.openActivity(this, REQUEST_DEPARTMENT, StringUtils.value(departId));
                break;
            case R.id.rl_grouping://分组
                GroupChooseActivity.openActivity(this, REQUEST_GROUP, groupMap);
                break;
            case R.id.rl_character://关联角色
                PersonChooseActivity.OpenActivity(this, REQUEST_PERSON, personId);
                break;
            case R.id.btn_start://启用
                engineerStatus = 1;
                btnStart.setBackgroundResource(R.drawable.shape_rb_left_pre);
                btnStart.setTextColor(getResources().getColor(R.color.white));
                btnClose.setBackgroundResource(R.drawable.shape_rb_right_nor);
                btnClose.setTextColor(getResources().getColor(R.color.color_333333));
                break;
            case R.id.btn_close://挂起
                engineerStatus = 2;
                btnStart.setBackgroundResource(R.drawable.shape_rb_left_nor);
                btnStart.setTextColor(getResources().getColor(R.color.color_333333));
                btnClose.setBackgroundResource(R.drawable.shape_rb_right_pre);
                btnClose.setTextColor(getResources().getColor(R.color.white));
                break;
            case R.id.rl_email://邮箱
                break;
            case R.id.rl_phone://电话
                break;
            case R.id.rl_contact://联系人
                break;
            case R.id.btn_determine_add://确定添加
                saveInfo();
                break;
            default:
                break;

        }
    }

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, AddEmployeeActivity.class);
        context.startActivity(intent);
    }

    /**
     * 保存信息
     */
    private void saveInfo() {
        String name = etName.getText().toString().trim();
        String number = etNumber.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String mail = etMail.getText().toString().trim();
        String mobile = etMobile.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            showCenterInfoMsg("姓名不能为空");
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            showCenterInfoMsg("手机号不能为空");
            return;
        }
        if (!FormatUtil.isMobileNO(phone)) {
            showCenterInfoMsg("请输入正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(departId)) {
            showCenterInfoMsg("部门不能为空");
            return;
        }
        if (arry == null || arry.length == 0 || TextUtils.isEmpty(StringUtils.value(arry[0]))) {
            showCenterInfoMsg("职能不能为空");
            return;
        }
        if (TextUtils.isEmpty(personId)) {
            showCenterInfoMsg("角色不能为空");
            return;
        }
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        String json = "";
        if ("1".equals(companyType)) {
            json = new Gson().toJson(new EmpSaveOwnerJsonBean(name, number, phone, gender, departId, personId, mail, mobile,
                    isForeign, engineerStatus, ownerBean.getRows().getEmployeeId(), arry[0], ownerBean.getRows().getOwnerCode()));
        } else if ("2".equals(companyType)) {
            json = new Gson().toJson(new EmpSaveServiceJsonBean(name, number, phone, gender, departId, personId, mail, mobile,
                    isForeign, engineerStatus, serviceLoginBean.getRows().getEmployeeId(), StringUtils.value(arry[0]), serviceLoginBean.getRows().getServiceProviderCode()));
        }
        manager.AddEmployee(this, json, this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_DEPARTMENT:
                    departId = intent.getStringExtra("id");
                    tvDepartment.setText(intent.getStringExtra("name"));
                    tvDepartment.setTextColor(mResource.getColor(R.color.color_333333));
                    break;
                case REQUEST_GROUP:
                    groupMap = (HashMap<String, String>) intent.getSerializableExtra("groupMap");
                    if (groupMap != null && groupMap.size() > 0) {
                        arry = JsonMapUtil.map2Array(groupMap);
                        tvFunction.setText(String.valueOf(arry[1]));
                        tvFunction.setTextColor(mResource.getColor(R.color.color_333333));
                    }
                    break;
                case REQUEST_PERSON:
                    personId = intent.getStringExtra("id");
                    tvCharacter.setText(intent.getStringExtra("name"));
                    tvCharacter.setTextColor(mResource.getColor(R.color.color_333333));
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        LogUtil.e("添加员工界面接口回掉 ---requestId：" + requestId + "result：" + result);
        CommonBean bean = new Gson().fromJson(result, CommonBean.class);
        if (bean.getMessage().getCode() == 200) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    EventBus.getDefault().post(new ContactsRefreshEvent());
                    showCenterSuccessMsg("添加成功");
                    finish();
                }
            }, 1500);
        } else if (bean.getMessage().getCode() == 1033) {
            showCenterInfoMsg("手机号已注册！");
        } else {
            showCenterInfoMsg(bean.getMessage().getMessage());
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showCenterInfoMsg("添加失败");
    }


}
